﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CosyTrade.Data;
using CosyTrade.Financial;
using CosyTrade.Organization;
using CosyTrade.Store;
using CosyTrade.Trade;
using CosyTrade.UI;
using DevExpress.XtraEditors.Controls;

namespace CosyTrade.ClientForm.Trade
{
    public partial class ExportDetailForm : DetailFormBase
    {
        private bool bindingEnable;

        ExportBill CurrentExportBill
        {
            get { return CurrentObject as ExportBill; }
        }

        public ExportDetailForm():this(Guid.Empty)
        {
            
        }

        public ExportDetailForm(Guid objKey) : base(objKey)
        {
            InitializeComponent();
        }

        protected override string GetTitle()
        {
            return "出口单详情";
        }

        protected override BusinessObject CreateNewBusinessObject()
        {
            return new ExportBill();
        }

        protected override BusinessObject InitBusinessObject(Guid currObjKey)
        {
            return Operation.TradeSystem.GetExportBillDetail(currObjKey);
        }
        
        protected override void DataBinding()
        {
            bindingEnable = false;
            if (CurrentExportBill == null) return;

            IList<Company> toCompanyList = Operation.OrganizationSystem.GetCompanyList();
            cbToCompany.Properties.Items.Clear();
            foreach (Company company in toCompanyList)
                if (company.CompanyType == CompanyType.Trade || company.CompanyType == CompanyType.Master)
                    cbToCompany.Properties.Items.Add(new ImageComboBoxItem(company.Caption, company));
            if (CurrentStat != DetailFormCurrentStat.AddStat)
            {
                foreach (Company company in toCompanyList)
                {
                    if (company.PrimaryKey == CurrentExportBill.ToCompany.PrimaryKey)
                    {
                        CurrentExportBill.ToCompany = company;
                        break;
                    }
                }
            }
            if (CurrentExportBill.ToCompany != null)
                BindingExchangeRate(CurrentExportBill.ToCompany.PrimaryKey);

            BindingControl(txtTradeCode, "EditValue", "TradeCode");
            BindingControl(cbToCompany, "EditValue", "ToCompany");
            BindingControl(txtFillBillEmployee, "EditValue", "FillBillEmployee");
            BindingControl(txtContainerNumber, "EditValue", "containerNumber");
            if (CurrentStat == DetailFormCurrentStat.AddStat)
                CurrentExportBill.FillBillEmployee = GlobalInfo.CurrentEmployee;
            BindingControl(txtTotalPackage, "EditValue", "PackageCount");
            BindingControl(txtTotalProductCount, "EditValue", "TotalCount");
            BindingControl(txtTotalMoney, "EditValue", "Total");
            BindingControl(txtCosidate, "EditValue", "ConsignmentDate");
            BindingControl(txtRecivdate, "EditValue", "FinishDate");
            //BindingControl(txtTotalMoney2, "EditValue", "Total2");
            txtTotalMoney2.EditValue = CurrentExportBill.Total2;

            bindingSource1.DataSource = CurrentExportBill.BillItems;
            bindingEnable = true;
        }

        protected override bool ControlCanVisible(Control control)
        {
            if (CurrentExportBill == null) return false;
            if (control == labConsi || control == txtCosidate)
                return CurrentExportBill.BillStat != ExportBillStat.Draft;
            if (control == labReciv || control == txtRecivdate)
                return CurrentExportBill.BillStat == ExportBillStat.Finish;

            if (control == labDP || control == txtAddPrice
                || control == lbTotal1 || control == lbTotal2 || control == txtTotalMoney || control == txtTotalMoney2
                || control == btnCaleBill)
                return GlobalInfo.CurrentRole.Powerset.Trade_ViewExportBillPrice;
            
            return true;
        }

        protected override bool ControlCanEdit(Control control)
        {
            if (control == txtFillBillEmployee) return false;
            if (control == txtTotalMoney2) return false;
            if (control == txtCosidate) return false;
            if (control == txtRecivdate) return false;
            return true;
        }

        protected override bool IsVail()
        {
            if (Functions.ValueIsEmpty(txtTradeCode) || string.IsNullOrEmpty(CurrentExportBill.TradeCode))
            {
                Functions.ShowMessageBox("请输入提单号");
                return false;
            }
            if (Functions.ValueIsEmpty(cbToCompany) || CurrentExportBill.ToCompany == null)
            {
                Functions.ShowMessageBox("请选择收货公司");
                return false;
            }
            if (Functions.ValueIsEmpty(cbExportRate) || CurrentExportBill.ExchangeRate==null)
            {
                Functions.ShowMessageBox("请选择出口汇率");
                return false;
            }
            if(bindingSource1.Count==0)
            {
                Functions.ShowMessageBox("请填写出口单的明细项");
                return false;
            }
            return true;
        }

        protected override void Save(BusinessObject currentObj)
        {
            ExportBill bill = currentObj as ExportBill;
            if (bill == null) return;

            switch (CurrentStat)
            {
                case DetailFormCurrentStat.AddStat:
                    Operation.TradeSystem.CreateExportBill(bill);
                    break;
                case DetailFormCurrentStat.EditStat:
                    Operation.TradeSystem.UpdateExportBill(bill);
                    break;
                case DetailFormCurrentStat.ViewStat:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        protected override void AfterRefreshEditStat()
        {
            addPanel.Visible = CurrentStat != DetailFormCurrentStat.ViewStat;
        }

        private void BindingExchangeRate(Guid companyGuid)
        {
            IList<ExchangeRate> rateLst = Operation.FinancialSystem.GetExchangeRateList(companyGuid);
            cbExportRate.Properties.Items.Clear();
            foreach (ExchangeRate rate in rateLst)
            {
                string msg = string.Format("{0}:汇率{1}", rate.ExchangeIndex, rate.Exchange);
                ImageComboBoxItem item = new ImageComboBoxItem(msg, rate);
                cbExportRate.Properties.Items.Add(item);
                if (CurrentExportBill.ExchangeRate != null && CurrentExportBill.ExchangeRate.PrimaryKey == rate.PrimaryKey)
                    cbExportRate.SelectedItem = item;
            }
        }

        private void CaleTotal2()
        {
            ExchangeRate selRate = cbExportRate.EditValue as ExchangeRate;
            if(selRate == null)
            {
                txtTotalMoney2.EditValue = 0;
                return;
            }

            double total = Convert.ToDouble(txtTotalMoney.EditValue.ToString());
            txtTotalMoney2.EditValue = total*selRate.Exchange;
        }

        private void cbExportRate_SelectedValueChanged(object sender, EventArgs e)
        {
            CaleTotal2();
        }

        private void txtTotalMoney_EditValueChanged(object sender, EventArgs e)
        {
            CaleTotal2();
        }

        private void txtFillBillEmployee_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            Employee emp = e.Value as Employee;
            if (emp != null) e.DisplayText = emp.EmpName;
        }

        private void productDropdownControl1_SelectedValue(object sender, EventArgs e)
        {
            popAddProduct.EditValue = productDropdownControl1.SelectedProduct;
            popAddProduct.ClosePopup();
        }

        private void productDropdownControl2_SelectedValue(object sender, EventArgs e)
        {
            ExportBillItem item = bindingSource1.Current as ExportBillItem;
            Company toComp = cbToCompany.EditValue as Company;
            if (item == null || toComp==null) return;
            item.Product = Operation.StoreManager.GetCompanyStore(toComp.PrimaryKey,
                                                                  productDropdownControl2.SelectedProduct.PrimaryKey);
            popupContainerControl2.OwnerEdit.ClosePopup();
        }

        private void btnAddExportItem_Click(object sender, EventArgs e)
        {
            Company toComp = cbToCompany.EditValue as Company;
            Product pro = popAddProduct.EditValue as Product;
            if (toComp == null)
            {
                Functions.ShowMessageBox("请先选择收货公司");
                return;
            }
            if (pro == null)
            {
                Functions.ShowMessageBox("请选择出口的商品");
                return;
            }
            if (Functions.ValueIsEmpty(txtAddTradeCode, "请输入商品编号")) return;
            if (Functions.ValueIsEmpty(popAddProduct, "请选择商品")) return;
            if (Functions.ValueIsEmpty(txtAddPrice)) txtAddPrice.EditValue = 0.0;
            if (Functions.ValueIsEmpty(txtAddIdCode, "请输入流水号")) return;
            if (Functions.ValueIsEmpty(txtAddPackageUnit, "请输入商品的装箱数 ")) return;
            if (Functions.ValueIsEmpty(txtAddProductCount, "请输入商品总数")) return;
            if (Functions.ValueIsEmpty(txtAddPackageCount, "请填写件数")) return;

            int totalCount = 0;
            if (!Functions.CheckNumber(txtAddProductCount.EditValue, ref totalCount))
            {
                Functions.ShowMessageBox("总商品数只能输入数值");
                return;
            }
            double totalWeight = 0.0;
            if (!Functions.CheckNumber(txtAddTotalWeight.EditValue, ref totalWeight))
            {
                Functions.ShowMessageBox("总重量只能输入数值");
                return;
            }
            int unitCount = 0;
            if (!Functions.CheckNumber(txtAddPackageUnit.EditValue, ref unitCount))
            {
                Functions.ShowMessageBox("装箱数只能输入数值");
                return;
            }
            int pageageCount = 0;
            if (!Functions.CheckNumber(txtAddPackageCount.EditValue, ref pageageCount))
            {
                Functions.ShowMessageBox("件数只能输入数值");
                return;
            }
            double price = 0.0;
            if (!Functions.CheckNumber(txtAddPrice.EditValue, ref price))
            {
                Functions.ShowMessageBox("价钱只能输入数值");
                return;
            }

            ExportBillItem item = new ExportBillItem();
            item.PackageCount = pageageCount;
            item.PackageRange = txtAddIdCode.Text;
            item.Price = price;
            item.Product = Operation.StoreManager.GetCompanyStore(toComp.PrimaryKey, pro.PrimaryKey);
            item.ShortCode = txtAddTradeCode.EditValue.ToString();
            item.TotalBulk = txtAddTotalBulk.EditValue as string;
            item.TotalCount = totalCount;
            item.TotalWeight = totalWeight;
            item.UnitCount = unitCount;
            bindingSource1.Add(item);
            CaleTotal();

            txtAddTradeCode.EditValue = txtAddTotalBulk.EditValue = txtAddIdCode.EditValue = string.Empty;
            txtAddProductCount.EditValue = txtAddPackageCount.EditValue = txtAddPackageUnit.EditValue = 0;
            txtAddTotalWeight.EditValue = txtAddPrice.EditValue = 0.0;
            popAddProduct.EditValue = null;
        }

        private void popAddProduct_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            Product pro = e.Value as Product;
            if (pro == null) return;
            e.DisplayText = pro.Caption;
        }

        private void rpyProduct_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            CompanyStore st = e.Value as CompanyStore;
            if (st == null) return;
            e.DisplayText = st.Products.Caption;
        }

        private void btnCaleBill_Click(object sender, EventArgs e)
        {
            CaleTotal();
        }

        private void CaleTotal()
        {
            ExportBill currBill = CurrentObject as ExportBill;
            if (currBill == null) return;

            currBill.Total = 0;
            currBill.TotalCount = 0;
            currBill.PackageCount = 0;

            foreach (ExportBillItem billItem in bindingSource1)
            {
                currBill.Total += billItem.TotalCount*billItem.Price;
                currBill.TotalCount += billItem.TotalCount;
                currBill.PackageCount += billItem.PackageCount;
            }
        }

        private void cbToCompany_EditValueChanged(object sender, EventArgs e)
        {
            if (!bindingEnable) return;

            Company cmp = cbToCompany.EditValue as Company;
            CurrentExportBill.ExchangeRate = null;
            if (cmp != null)
                BindingExchangeRate(cmp.PrimaryKey);
            Company newCmp = cbToCompany.EditValue as Company;
            if (newCmp == null)
            {
                bindingSource1.Clear();
                return;
            }
            foreach (ExportBillItem billItem in bindingSource1)
                billItem.Product = Operation.StoreManager.GetCompanyStore(newCmp.PrimaryKey, billItem.Product.Products.PrimaryKey);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            ExportBillItem delItem = bindingSource1.Current as ExportBillItem;
            if(delItem == null)
            {
                Functions.ShowMessageBox("请选择要移除的内容");
                return;
            }
            bindingSource1.RemoveCurrent();
            CaleTotal();
        }

        private void cbExportRate_EditValueChanged(object sender, EventArgs e)
        {
            CurrentExportBill.ExchangeRate = cbExportRate.EditValue as ExchangeRate;
        }

        private void ExportDetailForm_Load(object sender, EventArgs e)
        {
            colPrice.Visible = GlobalInfo.CurrentRole.Powerset.Trade_ViewExportBillPrice;
        }

        private void txtAddProductCount_EditValueChanged(object sender, EventArgs e)
        {
            Product product = popAddProduct.EditValue as Product;
            if (product == null) return;

            int totalCount = 0;
            if (!Functions.CheckNumber(txtAddProductCount.EditValue, ref totalCount))
            {
                Functions.ShowMessageBox("总商品数只能输入数值");
                return;
            }

            double bulk;
            double.TryParse(product.Bulk, out bulk);

            txtAddTotalWeight.EditValue = Math.Round(product.GrossWeight*totalCount, 2);
            txtAddTotalBulk.EditValue = Math.Round(bulk*totalCount, 2);
        }

        private void rpiBarcode_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            CompanyStore product = e.Value as CompanyStore;
            e.DisplayText = product == null ? "" : product.Products.BarCode;
        }

        private void txtAddPackageUnit_EditValueChanged(object sender, EventArgs e)
        {
            int pageageCount, unitCount;
            int.TryParse(txtAddPackageCount.EditValue.ToString(), out pageageCount);
            int.TryParse(txtAddPackageUnit.EditValue.ToString(), out unitCount);
            txtAddProductCount.EditValue = pageageCount*unitCount;
        }

        private void labelControl12_Click(object sender, EventArgs e)
        {

        }
    }
}
